﻿using DingTalk.Api.Response;
using DingTalk.Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;

namespace DingWeb.Controllers
{ 
    /// <summary>
    /// 登录
    /// </summary>
    public class LoginController : Controller
    {
        private readonly IRedisBasketRepository _cache;
        private readonly ILogger<LoginController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="cache"></param>
        public LoginController(ILogger<LoginController> logger, IRedisBasketRepository cache)
        {
            _logger = logger;
            _cache = cache;
        }

        public ActionResult Index()
        {
            List<QrCode> list = new List<QrCode>();
            list.Add(setModel("https://m.lvqdh.com/dingding/api/Home/DingLoginX", "dingoatfattz6p1jm3rjmn", "yMYsyRei2yeBV3dJyArKUhWY9cPAsckdOHiAB7gtJ4-3dzQ_01vN97cOAFAZLu3T"));
            list.Add(setModel("https://m.lvqdh.com/dingding/api/Home/DingLoginY", "dingoadee6ouocgpqmw6ub", "tRrypDJQ6PbuVIumBcEZNN7hWioRn8rK44vWN5mkCl5SVH111y2GTRl3Lz7Q0RWo"));
            list.Add(setModel("https://m.lvqdh.com/dingding/api/Home/DingLoginZ", "dingoalhyefruwhteteepl", "FzCx9B2GVjtHqKnfEkYf-jVv5h45rmeaJCW1uixuFqjL1O1e17C42jTj7FEl1CrM"));

            for (var i = 0; i < list.Count; i++)
            {
                OapiV2UserGetResponse res = _cache.Get<OapiV2UserGetResponse>("QR" + list[i].appid).Result;
                if (res == null)
                {
                    ViewBag.appid = list[i].appid;
                    ViewBag.backurl = list[i].backurl;

                    res = new OapiV2UserGetResponse()
                    {
                        Errcode = 0,
                        Errmsg = "初始化"
                    };
                    _cache.Set("QR" + list[i].appid, res, TimeSpan.FromSeconds(45)).Wait();//45秒过期
                    break;
                }
            }
            return View();
        }

        private QrCode setModel(string backurl, string appid, string appsecret)
        {
            QrCode data = new QrCode
            {
                name = "扫码登录测试",
                logourl = "https://www.hanfangyundu.com/web/Styles/img/logo2.png",
                backurl = backurl,
                appid = appid,
                appsecret = appsecret,
                statu = 0,
                datetime = DateTime.Now
            };
            return data;
        }
    }

    public class QrCode
    {
        public string name { get; set; }
        public string logourl { get; set; }
        public string backurl { get; set; }
        public string appid { get; set; }
        public string appsecret { get; set; }
        public int statu { get; set; }
        public DateTime datetime { get; set; }

    }
}
